var moment = require('moment');
var Promise = require('promise');
var apiLib = require('./MainApi');
var wms = require('./WmsApi');
const royal = require('./RoyalPay');
const wechat = require('./wechat');
var request = require('request');
var async = require('async');
// const WebSocket = require('ws');
// const ws = new WebSocket('ws://foo.com/anypath', {
//   perMessageDeflate: false
// });


module.exports = {
  index: function (req, res) {
    console.log(req.session);
    res.view('user');
  },
  //加入购物车，post方法，参数：sn，amount，返回状态，加入商品信息
  addToCart: function (req, res) {
    var sn = req.body.sn;
    var amount = Number(req.body.amount);
    var openId = req.body.openId;
    Cart.find({openId: openId, sn: sn}).then(function (result) {
      console.log(result)
      if (result.length>0) {
        Cart.update({openId: openId, sn: sn}, {amount: result[0].amount+amount}).then(function (updated) {
          res.send(updated);
        }).catch(function (err) {
          res.serverError(err);
        })
      } else {
        Cart.create({openId: openId, sn: sn, amount: amount}).then(function (created) {
          res.send(created);
        }).catch(function (err) {
          res.serverError(err);
        })
      }
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  deleteCart: function (req, res) {
    var openid = req.param('openid');
    var sn = req.params.sn;
    Cart.destroy({openId: openid, sn: sn}).exec(function (err) {
      if (err) return res.serverError(err);
      return res.ok('success');
    })
  },

  modifyCart: function (req, res) {
    console.log(req.body);
    Cart.update({openId: req.body.openid, sn: req.body.sn}, {amount: Number(req.body.amount)}).then(function (updated) {
      res.send('ok');
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  //传入参数:productId, amount, method: post, return product modified in json
  deleteFromCart: function (req, res) {
    var openId = req.session.openId;
    var id = req.body.id;
    var productId = req.body.productId;
    var amount = Number(req.body.amount);

    if (amount > 0) {
      Cart.update({id: id}, {amount: amount}).then(function (result) {
        res.send(result);
      }).catch(function (err) {
        res.serverError(err)
      })
    } else {
      // Cart.query('delete from sails_cart where id=?', [id], function (err, record) {
      //   if (err) return res.negotiate(err);
      //
      // })
      //Cart.destroy({openId: openId, productId: productId}).exec(function (err, record) {
      Cart.destroy([id]).exec(function (err, record) {
        if (err) return res.serverError(err);
        return res.send(record);
      })
    }
    // console.log(amount);
    // if (amount === 0) {
    //   Cart.destroy({id: id}).exec(function (err) {
    //     if (err) {
    //       return res.negotiate(err);
    //     }
    //     return res.send('ok');
    //   })
    // } else {
    //   Cart.update({id: id}, {amount: amount}).then(function (result) {
    //     res.send(result);
    //   }).catch(function (err) {
    //     res.serverError(err);
    //   })
    // }
  },

  cartView: function (req, res) {
    return res.view('cart');
  },

  cart: function (req, res) {
    console.log(req.session.user_info);
    var openId = req.param('openid');
    Cart.find({openId: openId}).then(function (result) {
      if (result.length == 0) {
        res.view('cartNew', {data: []});
      } else {
        var productInfo = [];
        // for (r in result) {
        //   var sn = result[i].sn;
        //   apiLib.getProductBySn(sn, function (call) {
        //     productInfo.push(JSON.parse(call)[0]);
        //     i++;
        //     if (i == result.length) {
        //       console.log(productInfo);
        //       royal.get_current_ex(function (rate) {
        //         res.view('cartNew', {data: productInfo, amount: result, rate: rate});
        //       })
        //     }
        //   })
        // }
        var get_products_info = new Promise(function (resolve, reject) {
          for (var i=0; i<result.length; i++){
            var get_product_info = new Promise(function (resolve, reject) {
              apiLib.getProductBySn(result[i].sn, function (call) {
                if (call.length > 0) {
                  resolve(JSON.parse(call)[0]);
                }
              })
            })
            Promise.all([get_product_info]).then(function (record) {
              productInfo.push(record[0]);
              if (productInfo.length == result.length) {
                resolve(productInfo);
              }
            })
          }
        })
        Promise.all([get_products_info]).then(function (p_arr) {
          royal.get_current_ex(function (rate) {
            res.view('cartNew', {data: p_arr[0], amount: result, rate: rate});
          })
        })
      }
    })
    // var openId = req.session.openId;
    // var products = [];
    //
    // Cart.find({openId: openId}).then(function (results) {
    //   console.log(results);
    //   if (results == 0) {
    //     res.send([]);
    //   } else {
    //   var productInfo = [];
    //   //var Promise = require('promise');
    //
    //   // var i = 0;
    //   // for (r in results) {
    //   //   console.log(r);
    //   //   Product.find({id: results[r].productId}).then(function (info) {
    //   //     productInfo.push(info);
    //   //     i++;
    //   //     if (i == results.length) {
    //   //       console.log(productInfo);
    //   //       res.send({info: productInfo, cart: results});
    //   //     }
    //   //   })
    //   // }
    //   for (var i=0; i<results.length; i++) {
    //     productInfo.push(Product.find({sn: results[i].productId}))
    //   }
    //   Promise.all(productInfo).then(function (info) {
    //       console.log(info);
    //       for (var i=0; i<results.length; i++) {
    //         results[i].info = info[i][0];
    //         if (i == results.length-1) {
    //           res.send({record: results, status: 'success'});
    //         }
    //       }
    //       //res.send({info: info, cart: results});
    //     }
    //   )}
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
  },

  confirmAddress: function (req, res) {
    var order_id = req.param('order_id');
    res.view('receive_addr', {id: order_id});
  },

  preOrder: function (req, res) {
    Order.create(req.body).then(function (record) {
      console.log(record);
      res.send(record.id);
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  getWmsid: function (req, res) {
    var order_id = req.param('order_id');
    Order.find({id: order_id}).then(function (record) {
      res.send(record);
    })
  },

  createOrder: function (req, res) {
    var orderId = req.body.orderId;
    var order_detail = JSON.parse(req.body.order);
    var receiver = order_detail.receiver_name+order_detail.receiver_phone+order_detail.receiver_addr;
    Order.update({id: orderId}, {status: '等待确认', receiver: receiver}).then(function (updated) {
      console.log('更改订单状态：',updated);
    }).catch(function (err) {
      res.serverError(err);
    });
    var order = req.body.order;
    var order_specs = req.body.order_specs;
    var reqBody = {
      order: order,
      order_specs: order_specs,
      default_packing_fee: '',
      customer: order_detail.customer,
      contact_sender: order_detail.contact_sender,
      contact_receiver: order_detail.contact_receiver,
    };
    wms.preOrder(reqBody, function (call) {
      console.log('order_id:', call)
      var order_id = JSON.parse(call);
      Order.update({id: orderId}, {wmsid: order_id}).then(function (update) {
        console.log('update wms order id');
      });
      var p_get_OrderDetail = new Promise(function(resolve, reject){
        wms.getOrderDetail(order_id, function (detail) {
          console.log('order_detail:',detail);
          if(detail && detail.length > 0){
            resolve(JSON.parse(detail)[0]);
          }
          else{
            reject('err')
          }
        });
      });
      var p_get_boxes = new Promise(function (resolve, reject) {
        wms.getBoxNo(order_id, function (boxes) {
          console.log(boxes);
          resolve(JSON.parse(boxes));
        });
      });
      Promise.all([
        p_get_OrderDetail,
        p_get_boxes
      ]).then(function(results){
        console.log('results:', results);
        res.send({order: results[0], boxes: results[1]});
      }).catch(function (err) {
        res.serverError(err);
      })
    })
  },

  confirmOrder: function (req, res) {
    // var orderId = req.body.order_id;
    // var order_products = req.body.products;
    // var amount = req.body.amount;
    // var receiver = req.body.receiver_info;
    // var order = req.body.order;
    // var wmsid = req.body.wmsid;
    // wms.getOrderDetail(wmsid, function (call) {

    // for(var i=0; i<order_products.length; i++){
    //   Cart.destroy({sn: order_products[i]}).then(function (result) {
    //     console.log('clean cart:',result);
    //   }).catch(function(err){
    //     res.serverError(err);
    //   })
    // };
    // Order.update({id: orderId}, {status: '等待付款', amount: amount, receiver: receiver}).then(function (updated) {
    //   res.send(updated);
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
    var order_id = req.param('order_id');
    Order.find({id: order_id}).then(function (record) {
      var products = JSON.parse(record[0].products);
      products.forEach(function (product) {
        var sn = product.sn;
        Cart.destroy({sn: sn}).then(function (result) {
          console.log('clean cart', result)
        })
      })
    });
    Order.update({id: order_id}, {status: '等待客服确认'}).then(function (updated) {
      console.log('update order status:',updated);
      res.ok('success');
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  getOrders: function (req, res) {
    var customer_id = req.param('customer_id');
    var order_status = req.param('status');
    wms.get_customer_orders_by_customer_id(customer_id, order_status, function (call) {
      async.forEachOf(call, function (v, k, callback) {
        wms.get_order_specs(v.id, function (detail) {
          console.log(call[k]);
          if (JSON.parse(detail).length > 0) {
            call[k]["p_sn"] = JSON.parse(detail)[0].sn;
          } else {
            call[k]["p_sn"] = 'nein';
          }
          console.log(detail);
          callback();
        })
      }, function (err) {
        if (err) console.log(err);
        res.send(call);
      })
      // var order_list = [];
      // for (var i=0; i<call.length; i++){
      //   var order_id = call[i].id;
      //   var json = call[i];
      //   var get_payment_status = new Promise(function (resolve, reject) {
      //     wms.get_order_payment(order_id, function (callback) {
      //       if (JSON.parse(callback).length > 0) {
      //         resolve(JSON.parse(callback));
      //       }
      //     })
      //   });
      //   Promise.all([get_payment_status]).then(function (result) {
      //     json['payment_status'] = result[0].status;
      //     order_list.push(json);
      //     if (order_list.length == call.length) {
      //       res.send(order_list);
      //     }
      //   })
      // }
    })
  },

  getPaymentStatus: function (req, res) {
    var order_id = req.param('order_id');
    wms.get_order_payment(order_id, function (call) {
      wms.get_order_specs(order_id, function (specs) {
        res.send({status: call, specs: JSON.parse(specs)});
      })
    })
  },

  myOrders: function (req, res) {
    // if (req.param('stat')) {
    //   var status = req.param('stat');
    //   Order.find({openid: req.session.user_info.openid, status: status}).then(function (result) {
    //     var i = 0;
    //     var info =[];
    //     for(r in result) {
    //       var order_id = result[r].wmsid;
    //       wms.getOrderDetail(order_id, function (call) {
    //         info.push(JSON.parse(call)[0]);
    //         i++;
    //         if (i == result.length) {
    //           console.log(info);
    //           res.view('myOrder', {orders: info});
    //         }
    //       })
    //     }
    //   })
    // } else {
    var openid = req.param('openid');
    res.view('myOrder');

      // Order.find({openid: openid}).then(function (record) {
      //   console.log(record);
      //   var i = 0;
      //   var info = [];
      //   var products = [];
      //   for (r in record) {
      //     var order_id = record[r].wmsid;
      //     var product_list = JSON.parse(record[i].products);
      //     // var product_info = new Promise(function (resolve, reject) {
      //     //   for(var j=0; j<product_list.length; j++){
      //     //     apiLib.getProductBySn(product_list[j].sn, function (info) {
      //     //       product_list[j].info = info;
      //     //     })
      //     //   };
      //     //   resolve(product_list);
      //     // });
      //
      //     wms.getOrderDetail(order_id, function (call) {
      //       info.push(JSON.parse(call)[0]);
      //       i++;
      //       if (i == record.length) {
      //         console.log(info);
      //         res.view('myOrder', {detail: info, orders: record});
      //       }
      //     })
      //   }
      // }).catch(function (err) {
      //   res.serverError(err);
      // })
  },

  orderInfo: function (req, res) {
    if (req.param('stat')) {

    }
  },
  //添加订单，传入参数：productId，amount，country，province，city，county，street，phone，name，openId，method：post
  addOrder: function (req, res) {
    var contactInfo = {phone: req.body.phone, name: req.body.name, country: req.body.country, province: req.body.province, city: req.body.city, street: req.body.street, openId: req.session.openId};
    Contact.findOrCreate(contactInfo).then(function (result) {
      return res.send(result);
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  order: function (req, res) {
    // var orderInfo = {amount: req.body.amount, contact: req.body.contact, quantity: req.body.quantity};
    // Order.create(orderInfo).then(function (result) {
    //   return res.send('ok');
    // })
    var orderId = req.params.id;
    var contact_id = req.param('contact_id');
    var customer_id = req.param('customer_id');
    console.log('customer id:',customer_id,'contact id:',contact_id);
    Order.find({id: orderId}).then(function (record) {
      console.log(record);
      var products = JSON.parse(record[0].products);
      console.log('product_list:', products);
      //var total = JSON.parse(record[0].total);
      var products_info = [];
      var get_products_info = new Promise(function (resolve, reject) {
        for (var i=0; i<products.length; i++){
          var sn = products[i].sn;
          var amount = products[i].amount;
          var get_product_info = new Promise(function (resolve, reject) {
            apiLib.getProductBySn(sn, function (call) {
              if (call.length > 0) {
                console.log('product info is: ', call);
                resolve(JSON.parse(call)[0]);
              }
            })
          });
          Promise.all([get_product_info]).then(function (record) {
            products_info.push({product: record[0], amount: amount});
            console.log(products_info);
            if (products_info.length == products.length) {
              resolve(products_info);
            }
          })
        }
      });
      Promise.all([get_products_info]).then(function (record) {
        console.log(record);
        wms.get_contact_by_id(customer_id, contact_id, function (call) {
          console.log('contact info:', call);
          res.view('order_confirm', {info: record[0], orderId: orderId, contact: call});
        })
      })
    })
  },

  // getAddresses: function (req, res) {
  //   Contact.find({openId: req.session.user_info.openid}).then(function (results) {
  //     res.send(results);
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  detail: function (req, res) {
    var productId = req.params.id;
    Product.find({id: productId}).then(function (result) {
      return res.view('detail', {layout: 'foo', data: result});
    })
  },

  // address : function(req, res){
  //   res.view('address');
  // },

  //修改地址，get方法传入addressId，返回相应地址信息
  // editAddress : function(req,res){
  //   var addressId = req.params.id;
  //   Contact.find({id: addressId}).then(function (record) {
  //     return res.view('editAddress', {data: record, layout: 'foo'});
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  //增加地址，post方法传入name, phone ,country, province, city, street信息,返回创建的地址信息
  // addAddress: function(req, res) {
  //   var address = JSON.parse(req.body.address);
  //   console.log(address.province);
  //   Contact.create(address).then(function (created) {
  //     res.send(created);
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  //地址列表，get方法获取该用户所有地址
  // getAddress: function (req, res) {
  //   var openId = req.session.openId;
  //   Contact.find({openId: openId}).then(function (record) {
  //     res.send({data: record, status: 'success'});
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  // getAddressById: function (req, res) {
  //   var addressId =  req.params.id;
  //   Contact.find({id: addressId}).then(function (record) {
  //     res.send(record);
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  // delAddressById: function (req, res) {
  //   var addressId = req.params.id;
  //   Contact.destroy([addressId]).then(function (record) {
  //     console.log(record);
  //     res.ok('success');
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  // //修改地址信息，post传入addressId以及修改后的相应信息，返回修改结果
  // updateAddress: function (req, res) {
  //   Contact.update({id: req.body.addressId}, {name: req.body.name, phone: req.body.phone, country: req.body.country, province: req.body.province, city: req.body.city, street: req.body.street, isDefault: req.body.isDefault, openId: req.session.openId}).then(function (result) {
  //     res.send({data: result, status: 'success'});
  //   }).catch(function (err) {
  //     res.serverError(err);
  //   })
  // },

  addOrderByCustomer: function (req, res) {
    var reqBody = req.body;

  },

  uploadPayment: function (req, res) {
    var openid = req.session.user_info.openid;
    console.log('user id:', openid);
    Order.find({openid: openid}).then(function (records) {
      var order_info = [];
      var i = 0;
      for(r in records){
        wms.getOrderDetail(records[r].wmsid, function (call) {
          order_info.push(JSON.parse(call)[0]);
          i++;
          if(i == records.length) {
            console.log('order_info:',order_info);
            res.view('upload_payment', {orders: order_info});
          }
        })
      }

    })
  },

  orderDetail: function (req, res) {
    var order_id = req.params.id;
    wms.getOrderDetail(order_id, function (call) {
      var order_detail = JSON.parse(call)[0];
      var products = order_detail.order_spec_summary.split(', ');
      var contact_id = order_detail.contact_receiver;
      var customer_id = order_detail.customer;
      var status = '';
      var o_status = order_detail.status;
      var p_status = order_detail.pmt_status;
      var d_status = order_detail.dlr_status;
      if (o_status < 5) {
        status = '等待客服确认';
      }
      if (o_status == 5 && p_status <13) {
        status = '等待支付';
      }
      if (o_status == 10 && p_status >= 13 && d_status < 40) {
        status = '支付成功，等待发货';
      }
      if (o_status == 10 && p_status >= 13 && d_status >=40) {
        status = '等待收货';
      }
      wms.get_order_specs(order_id, function (p_list) {
        wms.get_contact_by_id(customer_id, contact_id, function (call) {
          wms.getBoxNo(order_id, function (box_no) {
            var box_sn = box_no;
            res.view('order_detail', {p_list: JSON.parse(p_list), order: order_detail, contact: call, status: status, box_sn: box_sn});
          })
        })
      })
    })
    // Order.find({id: order_id}).then(function (record) {
    //   console.log('order detail:',record);
    //   var product_list = JSON.parse(record[0].products);
    //   var p_info = new Promise(function (resolve, reject) {
    //     var i = 0;
    //     var info = [];
    //     for(r in product_list){
    //       var sn = product_list[r].sn;
    //       apiLib.getProductBySn(sn, function (call) {
    //         info.push(JSON.parse(call)[0]);
    //         i++;
    //         if(i == product_list.length){
    //           resolve(info);
    //         }
    //       })
    //     }
    //   });
    //   var order_detail = new Promise(function (resolve, reject) {
    //     wms.getOrderDetail(record[0].wmsid, function (call) {
    //       resolve(JSON.parse(call)[0]);
    //     })
    //   });
    //   Promise.all([p_info, order_detail]).then(function (all) {
    //     console.log(all);
    //     res.view('order_detail', {info: all, order: record[0]});
    //   })
    // })
  },

  userInfo: function (req, res) {
    var openid = req.param('openid');
    User.find({openid: openid}).then(function (record) {
      if(typeof(record[0].phone) == 'undefined') {
        res.send('304');
      } else {
        res.send(record[0]);
      }
    })
  },

  bindPhone: function (req, res) {
    var json = req.body;
    wms.create_customer(json, function (call) {
      console.log('create customer:',call);
      res.ok('success');
    })
  },

  myAddress: function (req, res) {
    // var openid = req.param('openid');
    // Address.find({openid: openid}).then(function (records) {
    //   res.view('user_address', {data: records});
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
    res.view('user_address');
  },

  addAddress: function (req, res) {
    // Address.create(req.body).then(function (created) {
    //   console.log('created new address:', created);
    //   res.ok();
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
    var reqBody = req.body;
    var customer_id = req.param('customer_id');
    wms.create_customer_contact(customer_id, reqBody, function (call) {
      console.log('created customer contact:', call);
      res.ok('success');
    })
  },

  editAddress: function (req, res) {
    var address_id = req.param('');
    var customer_id = req.param('customer_id');
  },

  delAddress: function (req, res) {
    var address_id = req.params.id;
    Address.destroy({id: address_id}).exec(function (err) {
      if (err) return res.serverError(err);
      console.log('destroy address');
    })
  },

  addressDetail: function (req, res) {
    var address_id = req.param('addr');
    Address.find({id: address_id}).then(function (record) {
      res.view('edit_address', {data: record});
    })
  },

  addressAdd: function (req, res) {
    res.view('address');
  },

  allAddress: function (req, res) {
    // Address.find({openid: req.session.user_info.openid}).then(function (result) {
    //   res.send(result);
    // })
    var customer_id = req.param('customer_id');
    wms.get_customer_contacts(customer_id, function (call) {
      res.send(call);
    })
  },

  contactUs: function (req, res) {
    res.view('contact_us');
  },

  wechatNotify: function (req, res) {
    console.log('reqbody: ', req.body);
    var order_id = req.body.order_id;
    var order_sn = req.body.order_sn;
    var msg_type = req.body.msg_type;
    var order_specs = req.body.order_specs;
    var time_stamp = Number(req.body.timestamp);
    var time = moment(time_stamp).format('YYYY-MM-DD hh时mm分');
    Order.find({wmsid: order_id}).then(function (record) {
      var openid = record[0].openid;
      var body = {
        "touser": openid,
        "template_id": "vjvcA1S2idw7Jc5E1jGT34fF38IfVjiGQtS4I2mO2Sw",
        "url": 'http://www.auewecanberra.com/users/orders/'+order_id,
        "data": {},
      };
      var json = {};
      switch (msg_type) {
        case 'created':
          json = {
            "first": {"value": '订单提交成功！'},
            "keyword1": {"value": time},
            "keyword2": {"value": order_specs},
            "keyword3": {"value": order_sn},
            "remark": {"value": '成功创建订单！'}
          };
          break;
        case 'confirmed':
          json = {
            "first": {"value": '客服已确认订单'},
            "keyword1": {"value": time},
            "keyword2": {"value": order_specs},
            "keyword3": {"value": order_sn},
            "remark": {"value": '客服已确认订单商品内容，可以前去支付'}
          };
          break;
        case 'paid':
          json = {
            "first": {"value": '订单支付成功'},
            "keyword1": {"value": time},
            "keyword2": {"value": order_specs},
            "keyword3": {"value": order_sn},
            "remark": {"value": '订单支付成功，等待发货'}
          };
          break;
        case 'screenshot_err':
          json = {
            "first": {"value": '转账截图有误'},
            "keyword1": {"value": time},
            "keyword2": {"value": order_specs},
            "keyword3": {"value": order_sn},
            "remark": {"value": '订单转账截图有误，请重新上传'}
          };
          break;
      }
      body.data = json;
      wechat.getAccessToken(function(token){
        request({
          url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+token,
          method: 'POST',
          json: true,
          headers: {
            'Content-Type': 'application/json'
          },
          body: body,
      }, function(err, resp, body){
          if (err) return res.serverError(err);
          if (body.errcode == 0) {
            res.ok('success');
        }
      })
    })
  });
  },

  getCart: function (req, res) {
      var openid = req.params.openid;
      Cart.find({openId: openid}).then(function (records) {
        if (records.length == 0) {
          res.send([]);
        } else {
          var p_list = [];
          var get_p_info = new Promise(function (resolve, reject) {
            for (var i = 0; i < records.length; i++) {
              var sn = records[i].sn;
              var amount = records[i].amount;
              apiLib.getProductBySn(sn, function (call) {
                p_list.push({product: JSON.parse(call)[0], amount: amount});
                if (p_list.length == records.length) {
                  resolve(p_list);
                }
              });
            }
          });
          Promise.all([get_p_info]).then(function (result) {
            res.send(result[0]);
          })
        }
      })
    },

}
